package core.android.tools;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 缓存线程池
 */
public class AKThreadPool {
    public static final String TAG = AKThreadPool.class.getSimpleName();
    static Executor threadPool=createExecutor(5);
    static Handler mainThreadHandler = new Handler(Looper.getMainLooper());

    /**
     * 此线程池执行2444个任务,不会造成内存一出.by xq 20151112
     * @param threadPoolSize
     * @return
     */
    public static Executor createExecutor(int threadPoolSize) {
        BlockingQueue taskQueue = new LinkedBlockingQueue();
        return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0L, TimeUnit.MILLISECONDS, taskQueue);
    }

    public synchronized static void go(Runnable runnable){
        if(null == threadPool){
           AK.d( "ThreadPool没有被初始化，请在Application中进行初始化操作...");
            return;
        }
        threadPool.execute(runnable);
    }

    /**
     * 去主UI线程中运行
     * @param r
     */
    public static void gomain(Runnable r) {
        if(null == mainThreadHandler){
           AK.d( "ThreadPool没有被初始化，请在Application中进行初始化操作...");
            return;
        }
        mainThreadHandler.post(r);
    }

    /**
     * 去主UI线程中延迟delayMillis毫秒运行
     * @param r
     * @param delayMillis 毫秒ms
     */
    public static void gomain(Runnable r, long delayMillis) {
        if(null == mainThreadHandler){
           AK.d( "ThreadPool没有被初始化，请在Application中进行初始化操作...");
            return;
        }
        mainThreadHandler.postDelayed(r,delayMillis);
    }
}
